package com.szit.adminserver.server.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.szit.adminserver.dao.AdminPermissionMapper;
import com.szit.adminserver.dao.AdminRoleMapper;
import com.szit.adminserver.dao.AdminUserMapper;
import com.szit.adminserver.dao.AdminUserRoleMapper;
import com.szit.adminserver.entity.AdminUser;
import com.szit.adminserver.entity.AdminUserRole;
import com.szit.adminserver.server.AdminUserServer;
import com.szit.util.CodeMsg;
import com.szit.util.MD5Util;
import com.szit.util.Result;
import com.szit.util.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import java.util.*;

import static com.szit.util.Result.success;

@Slf4j
@Service
public class AdminUserServerImpl implements AdminUserServer {

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @Autowired
    private AdminUserRoleMapper adminUserRoleMapper;

    @Autowired
    private AdminPermissionMapper adminPermissionMapper;

    /**
     * 登录
     *
     * @param loginUser
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result login(LoginUser loginUser) {
        try {
            if(StringUtils.isEmpty(loginUser) &&
                    StringUtils.isEmpty(loginUser.getUsername()) &&
                    StringUtils.isEmpty(loginUser.getPassword()) ){
                log.info("adminUserInfo--------参数为空");
                return Result.error(CodeMsg.PARAMETER_ISNULL);
            }
            AdminUser cAdminUser = adminUserMapper.selectByUsername(loginUser.getUsername());
            log.info("--------判断当前用户是否存在---------");
            if(StringUtils.isEmpty(cAdminUser)){
                log.info("-------目标用户不存在--------");
                return Result.error(CodeMsg.USER_NOT_EXSIST);
            }
            /*原加密盐*/
            String oslat = cAdminUser.getSalt();
            /*原密码*/
            String oPass = cAdminUser.getPassword();
            /*token*/
            String token = UUID.randomUUID().toString().replaceAll("-","");
            log.info("-------检查密码-------");
            if (!oPass.equals(MD5Util.getMD5(loginUser.getPassword(), oslat))) {
                log.info("-------密码错误-------");
                return Result.error(CodeMsg.USER_PASSWORD_EXSIST);
            }

            log.info("-------密码正确，插入token-------");
            cAdminUser.setToken(token);
            adminUserMapper.updateByPrimaryKeySelective(cAdminUser);

            log.info("--------获取当前用户权限---------");
            Long cOrder =  adminPermissionMapper.selectOrdersByUserId(cAdminUser.getUserId());

            Map<String,Object> map = new HashMap<>();
            map.put("Orders",cOrder);
            map.put("User",cAdminUser);

            return success(map);
        }catch (Exception e){
            e.printStackTrace();
            /*手工回滚异常*/
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error(CodeMsg.SERVER_EXCEPTION);
        }
    }

    /**
     * 登出
     *
     * @param token
     * @return
     */
    @Override
    public Result loginOut(String token) {
        return success();
    }

    /**
     * 根据用户名修改用户密码
     *
     * @param modifyPasswordInfo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result updatePasswordByUsername(ModifyPasswordInfo modifyPasswordInfo) {
        try {
            if(StringUtils.isEmpty(modifyPasswordInfo) &&
                    StringUtils.isEmpty(modifyPasswordInfo.getToken()) &&
                    StringUtils.isEmpty(modifyPasswordInfo.getModifyUsername()) &&
                    StringUtils.isEmpty(modifyPasswordInfo.getOldPassword()) &&
                    StringUtils.isEmpty(modifyPasswordInfo.getNewPassword()) ){
                log.info("modifyPasswordInfo--------参数为空");
                return Result.error(CodeMsg.PARAMETER_ISNULL);
            }

            AdminUser cAdminUser = adminUserMapper.selectByToken(modifyPasswordInfo.getToken());
            AdminUser mAdminUser = adminUserMapper.selectByUsername(modifyPasswordInfo.getModifyUsername());
            if(StringUtils.isEmpty(cAdminUser)||StringUtils.isEmpty(mAdminUser)){
                log.info("-------目标用户不存在--------");
                return Result.error(CodeMsg.USER_NOT_EXSIST);
            }
            /*原加密盐*/
            String oslat = mAdminUser.getSalt();
            /*原密码*/
            String oPass = mAdminUser.getPassword();
            /*新加密盐*/
            String nslat = UUID.randomUUID().toString().replaceAll("-","");
            log.info("-------检查原密码-------");
            if (!oPass.equals(MD5Util.getMD5(modifyPasswordInfo.getOldPassword(), oslat))) {
                log.info("-------原密码错误-------");
                return Result.error(CodeMsg.USER_PASSWORD_EXSIST);
            }
            if(!cAdminUser.getUsername().equals(modifyPasswordInfo.getModifyUsername())){
                log.info("-------当前用户与目标用户不一致-------");
                Long cOrder =  adminPermissionMapper.selectOrdersByUserId(cAdminUser.getUserId());
                Long mOrder =  adminPermissionMapper.selectOrdersByUserId(mAdminUser.getUserId());
                if(StringUtils.isEmpty(cOrder)||StringUtils.isEmpty(mOrder)){
                    log.info("-------未知权限值-------");
                    return Result.error(CodeMsg.SERVER_EXCEPTION);
                }
                if(cOrder >= mOrder){
                    log.info("-------权限不足-------");
                    return Result.error(CodeMsg.NO_PERMISSIONS);
                }else{

                    String nPass = MD5Util.getMD5(modifyPasswordInfo.getNewPassword(),nslat);

                    log.info("-------原密码正确，修改密码-------");
                    mAdminUser.setSalt(nslat);
                    mAdminUser.setPassword(nPass);
                    adminUserMapper.updateByPrimaryKeySelective(mAdminUser);

                    return success(CodeMsg.SUCCESS);
                }
            }else {
                log.info("-------当前用户与目标用户一致-------");

                String nPass = MD5Util.getMD5(modifyPasswordInfo.getNewPassword(),nslat);

                log.info("-------原密码正确，修改密码-------");
                mAdminUser.setSalt(nslat);
                mAdminUser.setPassword(nPass);
                adminUserMapper.updateByPrimaryKeySelective(mAdminUser);

                return success(CodeMsg.SUCCESS);

            }
        }catch (Exception e){
            e.printStackTrace();
            /*手工回滚异常*/
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error(CodeMsg.SERVER_EXCEPTION);
        }
    }

    /**
     * 添加子用户
     *
     * @param adminUserInfo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result insertAdminUser(AdminUserInfo adminUserInfo) {
        try {
            if(StringUtils.isEmpty(adminUserInfo) &&
                    StringUtils.isEmpty(adminUserInfo.getToken()) &&
                    StringUtils.isEmpty(adminUserInfo.getUsername()) &&
                    StringUtils.isEmpty(adminUserInfo.getPassword()) &&
                    StringUtils.isEmpty(adminUserInfo.getRoleId())){
                log.info("adminUserInfo--------参数为空");
                return Result.error(CodeMsg.PARAMETER_ISNULL);
            }
            AdminUser cAdminUser = adminUserMapper.selectByToken(adminUserInfo.getToken());
            if(StringUtils.isEmpty(cAdminUser)){
                log.info("--------token无效---------");
                return Result.error(CodeMsg.SESSION_NOT_EXSIST);
            }
            log.info("--------获取当前用户权限---------");
            Long cOrder =  adminPermissionMapper.selectOrdersByUserId(cAdminUser.getUserId());
            if(cOrder > 2 ||adminUserInfo.getRoleId() == 1){
                log.info("--------当前用户权限不足---------");
                return Result.error(CodeMsg.NO_PERMISSIONS);
            }
            log.info("--------查询用户名是否存在--------");
            AdminUser adminUser = adminUserMapper.selectByUsername(adminUserInfo.getUsername());
            if(!StringUtils.isEmpty(adminUser)){
                log.info("--------用户名是已存在--------");
                return Result.error(CodeMsg.USER_IS_EXSIST);
            }
            log.info("--------添加子用户--------");
            String nslat = UUID.randomUUID().toString().replaceAll("-","");
            String nPass = MD5Util.getMD5(adminUserInfo.getPassword(),nslat);
            adminUser = new AdminUser();
            adminUser.setUsername(adminUserInfo.getUsername());
            adminUser.setPassword(nPass);
            adminUser.setSalt(nslat);
            adminUser.setLocked((byte) 0);
            adminUser.setCtime(new Date());
            adminUserMapper.insertSelective(adminUser);

            log.info("--------查询刚刚添加的用户id--------");
            AdminUser adminUser1 = adminUserMapper.selectByUsername(adminUserInfo.getUsername());
            log.info("--------添加用户角色关联--------");
            AdminUserRole adminUserRole = new AdminUserRole();
            adminUserRole.setRoleId(adminUserInfo.getRoleId());
            adminUserRole.setUserId(adminUser1.getUserId());
            adminUserRoleMapper.insertSelective(adminUserRole);


            return success(CodeMsg.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            /*手工回滚异常*/
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error(CodeMsg.SERVER_EXCEPTION);
        }
    }

    /**
     * 删除用户
     *
     * @param token
     * @param userId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result deleteAdminUserByUserId(String token, Integer userId) {
        try {
            if(StringUtils.isEmpty(token) &&
                    StringUtils.isEmpty(userId) ){
                log.info("token---userId-------参数为空");
                return Result.error(CodeMsg.PARAMETER_ISNULL);
            }
            AdminUser cAdminUser = adminUserMapper.selectByToken(token);
            if(StringUtils.isEmpty(cAdminUser)){
                log.info("--------token无效---------");
                return Result.error(CodeMsg.SESSION_NOT_EXSIST);
            }
            log.info("--------获取当前用户权限---------");
            Long cOrder =  adminPermissionMapper.selectOrdersByUserId(cAdminUser.getUserId());
            if(cOrder > 2 ){
                log.info("--------当前用户权限不足---------");
                return Result.error(CodeMsg.NO_PERMISSIONS);
            }

            log.info("--------删除子用户---------");
            adminUserMapper.deleteByPrimaryKey(userId);

            return success(CodeMsg.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            /*手工回滚异常*/
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error(CodeMsg.SERVER_EXCEPTION);
        }
    }

    /**
     * 查找所有用户
     *
     * @param token
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Result selectAllUser(String token, Integer pageNum, Integer pageSize) {
        try {
            if(StringUtils.isEmpty(token)){
                log.info("token--------参数为空");
                return Result.error(CodeMsg.PARAMETER_ISNULL);
            }
            if(StringUtils.isEmpty(pageNum)){
                pageNum = 1;
            }
            if(StringUtils.isEmpty(pageSize)){
                pageSize = 10;
            }
            AdminUser cAdminUser = adminUserMapper.selectByToken(token);
            if(StringUtils.isEmpty(cAdminUser)){
                log.info("--------token无效---------");
                return Result.error(CodeMsg.SESSION_NOT_EXSIST);
            }
            log.info("--------获取当前用户权限---------");
            Long cOrder =  adminPermissionMapper.selectOrdersByUserId(cAdminUser.getUserId());
            if(cOrder > 3 ){
                log.info("--------当前用户权限不足---------");
                return Result.error(CodeMsg.NO_PERMISSIONS);
            }

            log.info("--------查询所有用户---------");
            /*分页插件 传入页数和每页数量*/
            PageHelper.startPage(pageNum, pageSize);
            ArrayList<AdminUserVo> list = adminUserMapper.selectRoleIdAndAllUser();
            PageInfo pageInfo = new PageInfo(list);

            return success(pageInfo);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(CodeMsg.SERVER_EXCEPTION);
        }
    }

    /**
     * 根据token查找用户并返回order,供其他服务调用
     *
     * @param token
     * @return
     */
    @Override
    public Result selectAdminUserByToken(String token) {
        if(StringUtils.isEmpty(token)){
            log.info("token--------参数为空");
            return Result.error(CodeMsg.PARAMETER_ISNULL);
        }
        AdminUser cAdminUser = adminUserMapper.selectByToken(token);
        if(StringUtils.isEmpty(cAdminUser)){
            log.info("--------token无效---------");
            return Result.error(CodeMsg.SESSION_NOT_EXSIST);
        }
        log.info("--------获取当前用户权限---------");
        Long cOrder =  adminPermissionMapper.selectOrdersByUserId(cAdminUser.getUserId());

        return Result.success(cOrder);
    }

    /**
     * 更改用户角色
     *
     * @param adminUserRoleInfo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result updateUserRoleByUserId(AdminUserRoleInfo adminUserRoleInfo) {
        try {
            if(StringUtils.isEmpty(adminUserRoleInfo) &&
                    StringUtils.isEmpty(adminUserRoleInfo.getToken()) &&
                    StringUtils.isEmpty(adminUserRoleInfo.getUserId()) &&
                    StringUtils.isEmpty(adminUserRoleInfo.getRoleId())){
                log.info("adminUserInfo--------参数为空");
                return Result.error(CodeMsg.PARAMETER_ISNULL);
            }
            AdminUser cAdminUser = adminUserMapper.selectByToken(adminUserRoleInfo.getToken());
            if(StringUtils.isEmpty(cAdminUser)){
                log.info("--------token无效---------");
                return Result.error(CodeMsg.SESSION_NOT_EXSIST);
            }
            log.info("--------获取当前用户权限---------");
            Long cOrder =  adminPermissionMapper.selectOrdersByUserId(cAdminUser.getUserId());
            if(cOrder > 2 ){
                log.info("--------当前用户权限不足---------");
                return Result.error(CodeMsg.NO_PERMISSIONS);
            }

            log.info("--------查询该用户角色关联--------");
            AdminUserRole adminUserRole = adminUserRoleMapper.selectByUserId(adminUserRoleInfo.getUserId());
            if (StringUtils.isEmpty(adminUserRole)){
                log.info("--------用户无角色，新增用户角色--------");
                adminUserRole = new AdminUserRole();
                adminUserRole.setUserId(adminUserRoleInfo.getUserId());
                adminUserRole.setRoleId(adminUserRoleInfo.getRoleId());
                log.info("--------新增用户角色--------");
                adminUserRoleMapper.insertSelective(adminUserRole);
            }else{
                log.info("--------用户有角色，更改用户角色--------");
                adminUserRole.setRoleId(adminUserRoleInfo.getRoleId());
                log.info("--------更改用户角色--------");
                adminUserRoleMapper.updateByPrimaryKeySelective(adminUserRole);
            }

            return success(CodeMsg.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            /*手工回滚异常*/
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error(CodeMsg.SERVER_EXCEPTION);
        }
    }

    /**
     * 删除用户角色
     *
     * @param adminUserRoleInfo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result deleteAdminUserRole(AdminUserRoleInfo adminUserRoleInfo) {
        try {
            if(StringUtils.isEmpty(adminUserRoleInfo) &&
                    StringUtils.isEmpty(adminUserRoleInfo.getToken()) &&
                    StringUtils.isEmpty(adminUserRoleInfo.getUserId())){
                log.info("token---userId-------参数为空");
                return Result.error(CodeMsg.PARAMETER_ISNULL);
            }
            AdminUser cAdminUser = adminUserMapper.selectByToken(adminUserRoleInfo.getToken());
            if(StringUtils.isEmpty(cAdminUser)){
                log.info("--------token无效---------");
                return Result.error(CodeMsg.SESSION_NOT_EXSIST);
            }
            log.info("--------获取当前用户权限---------");
            Long cOrder =  adminPermissionMapper.selectOrdersByUserId(cAdminUser.getUserId());
            if(cOrder > 2 ){
                log.info("--------当前用户权限不足---------");
                return Result.error(CodeMsg.NO_PERMISSIONS);
            }

            log.info("--------查找用户角色关联---------");
            AdminUserRole adminUserRole = adminUserRoleMapper.selectByUserId(adminUserRoleInfo.getUserId());
            if (StringUtils.isEmpty(adminUserRole)){
                log.info("--------用户无绑定角色---------");
                return Result.error(CodeMsg.NOT_FIND_DATA);
            }

            log.info("--------用户删除角色---------");
            adminUserRoleMapper.deleteByPrimaryKey(adminUserRole.getUserRoleId());


            return success(CodeMsg.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            /*手工回滚异常*/
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error(CodeMsg.SERVER_EXCEPTION);
        }
    }
}
